<template>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    title="修改设备配置文件"
    @ok="handleSubmit"
    width="700px"
    :destroyOnClose="true"
    :closeFunc="close"
    :body-style="{ marginLeft: '10px', marginRight: '10px' }"
  >
    <Tabs v-model:activeKey="activeKey" :animated="true" centered>
      <TabPane key="detail" tab="详情">
        <EditDeviceFileDetail
          :formData="deviceFileData"
          ref="editFileDetailForm"
          @upload="getImgData"
          @delete-img="deleteImgData"
        />
      </TabPane>
      <TabPane key="transport" tab="传输配置">
        <TransportConfiguration
          :formData="transportConfiguration"
          ref="editTransportConfiguration"
        />
      </TabPane>
      <TabPane key="alarms" tab="告警规则">
        <Alarm ref="editAlarm" :formData="alarm" />
      </TabPane>
      <TabPane key="device" tab="设备预配置">
        <DeviceFilePreConfiguredForm
          :formData="provisionConfiguration"
          ref="editDeviceFilePreConfiguredForm"
        />
      </TabPane>
    </Tabs>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Tabs, TabPane } from 'ant-design-vue';
  // import { editTabListData } from '../deviceDrawer.data';
  import EditDeviceFileDetail from './EditDeviceFileDetail.vue';
  import {
    postDeviceProfile,
    getDeviceProfileById,
  } from '/@/api/thingsborad/profile/deviceProfile/deviceProfile';
  import DeviceFilePreConfiguredForm from '/@/components/thingsborad/sharedComponents/modules/addDeviceFileModel/DeviceFilePreConfiguredForm.vue';
  import TransportConfiguration from '/@/components/thingsborad/sharedComponents/modules/addDeviceFileModel/TransportConfiguration.vue';
  import Alarm from '/@/components/thingsborad/sharedComponents/modules/addDeviceFileModel/Alarm/Alarm.vue';
  import { ref, watch, provide } from 'vue';
  // let data = ref({});
  const emit = defineEmits(['edit']);
  let activeKeyFlag = ref<Recordable>({
    detail: true,
    transport: false,
    alarms: false,
    device: false,
  });
  // const TabsList = ref(editTabListData);
  const deviceFileData = ref<Recordable>({});
  const provisionConfiguration = ref<Recordable>({});
  const transportConfiguration = ref<Recordable>({});
  let alarm = ref([]);
  let imgData = ref(null);
  let activeKey = ref('detail');
  // deviceFileDetailForm设备配置详情表单实例
  const editFileDetailForm = ref<any>(null);
  const editDeviceFilePreConfiguredForm = ref<any>(null);
  //transportConfiguration 传输配置表单实例
  const editTransportConfiguration = ref<any>(null);
  const editAlarm = ref<any>({});
  let deviceId = ref('');
  watch(
    () => activeKey.value,
    (nVal) => {
      activeKeyFlag.value[nVal] = true;
    },
    { immediate: true },
  );
  const [registerModal, { closeModal }] = useModalInner(async (data) => {
    try {
      let param = '/' + data.record.id;
      deviceId.value = data.record.id;
      await getDeviceProfileById(param).then((res) => {
        deviceFileData.value = res;
      });
    } catch (error) {
      console.error('获取配置信息失败', error);
    }

    provisionConfiguration.value = deviceFileData.value.profileData.provisionConfiguration;
    provisionConfiguration.value.provisionDeviceKey = deviceFileData.value.provisionDeviceKey;
    transportConfiguration.value = deviceFileData.value.profileData.transportConfiguration;
    alarm.value = deviceFileData.value.profileData.alarms;
  });
  provide('isEditModel', true);
  provide('deviceId', deviceId);
  function getImgData(data: any) {
    imgData.value = data;
  }
  function deleteImgData() {
    imgData.value = null;
  }
  async function close() {
    imgData.value = null;
    activeKey.value = 'detail';
    activeKeyFlag.value = {
      detail: true,
      transport: false,
      alarms: false,
      device: false,
    };
    return true;
  }
  async function handleSubmit() {
    //详情
    if (activeKeyFlag.value.detail) {
      await editFileDetailForm.value.validate().then((res) => {
        if (res.defaultDashboardId != undefined) {
          res.defaultDashboardId = JSON.parse(res.defaultDashboardId);
        }
        if (res.defaultEdgeRuleChainId != undefined) {
          res.defaultEdgeRuleChainId = JSON.parse(res.defaultEdgeRuleChainId);
        }
        if (res.defaultRuleChainId != undefined) {
          res.defaultRuleChainId = JSON.parse(res.defaultRuleChainId);
        }
        res.image = imgData.value;

        Object.assign(deviceFileData.value, res);
      });
    }
    //传输配置
    if (activeKeyFlag.value.transport) {
      await editTransportConfiguration.value.getTransportConfiguration().then((res) => {
        deviceFileData.value.transportType = res.type;
        deviceFileData.value.profileData.transportConfiguration = res;
      });
    }
    //告警
    if (activeKeyFlag.value.alarms) {
      deviceFileData.value.profileData.alarms = editAlarm.value.getAlarmsData();
      if (deviceFileData.value.profileData.alarms === undefined) {
        return;
      }
    }
    //设备预配置
    if (activeKeyFlag.value.device) {
      let res = await editDeviceFilePreConfiguredForm.value.validate();

      deviceFileData.value.provisionType = res.type;
      if (res.certificateRegExPattern) {
        res.provisionDeviceSecret = res.PEMprovisionDeviceSecret;
        res.certificateValue = res.PEMprovisionDeviceSecret;
        deviceFileData.value.provisionDeviceKey = null;
      } else {
        deviceFileData.value.provisionDeviceKey = '';
        deviceFileData.value.provisionDeviceKey = res.provisionDeviceKey;
      }
      deviceFileData.value.profileData.provisionConfiguration = {};
      deviceFileData.value.profileData.provisionConfiguration = res;
    }

    try {
      await postDeviceProfile(deviceFileData.value);
    } catch (error) {
      console.error('修改设备配置失败', error);
    }
    if (activeKeyFlag.value.detail) {
      editFileDetailForm.value.resetFields();
    }
    if (activeKeyFlag.value.device) {
      editDeviceFilePreConfiguredForm.value.resetFields();
    }
    activeKey.value = 'detail';
    activeKeyFlag.value = {
      detail: true,
      transport: false,
      alarms: false,
      device: false,
    };
    emit('edit');
    imgData.value = null;
    closeModal();
  }
</script>
